package wxutil

import (
	"context"
	"time"
	"zhonghui/console/warehouse/dbx/cache_main"

	jsoniter "github.com/json-iterator/go"

	"github.com/go-redis/redis/v8"
)

// Cache is a cache interface
type CacheInterface interface {
	// Get gets value by key
	Get(key string) (interface{}, error)
	// Set sets value with key and expire time
	Set(key string, val interface{}, timeout int64) error
	// Delete deletes value by key
	Delete(key string) error
	// IsExist returns true if value exists
	IsExist(key string) bool
	// ClearAll clears all cache
	ClearAll() error
}

type Cache struct {
	client *redis.Client
}

func NewCache() *Cache {
	return &Cache{
		client: cache_main.Client(),
	}
}

func (c *Cache) Client() *redis.Client {
	return c.client
}

func (c *Cache) Get(key string) (interface{}, error) {
	return c.client.Get(context.Background(), key).Result()
}

func (c *Cache) Set(key string, val interface{}, timeout time.Duration) error {
	r, err := jsoniter.Marshal(val)
	if err != nil {
		return err
	}
	return c.client.Set(context.Background(), key, r, timeout).Err()
}
